package com.ruoyi.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.dto.ItemDTO;
import com.ruoyi.api.dto.OrderDTO;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.IdGenerator;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductCart;
import com.ruoyi.product.domain.ProductImg;
import com.ruoyi.product.domain.ProductPrice;
import com.ruoyi.product.dto.*;
import com.ruoyi.product.service.*;
import com.ruoyi.system.domain.Orders;
import com.ruoyi.system.domain.OrdersItem;
import com.ruoyi.system.service.IOrdersItemService;
import com.ruoyi.system.service.IOrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 产品分类Controller
 *
 * @author ruoyi
 * @date 2020-12-27
 */
@RestController
@RequestMapping("/api/order")
@Api(tags = "订单接口")
public class ApiOrderController extends ApiBaseController {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrdersItemService ordersItemService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductImgService productImgService;

    @Autowired
    private IProductPriceService productPriceService;

    @Autowired
    private IProductCartService productCartService;

    private ProductPrice convert(Long productId,String priceId){
        ProductPrice productPrice = new ProductPrice();
        productPrice.setProductId(productId);
        List<ProductPrice> lst = productPriceService.selectProductPriceList(productPrice);
        for(ProductPrice p : lst){
            if((p.getKeyId()+"").equals(priceId)){
                return p;
            }
        }
        return  null;
    }
    @PostMapping("/submitDetailPage")
    @ApiOperation("产品详情提交订单接口")
    @ResponseBody
    public AjaxResult submitDetailPage(Long storeId,String json){
        Long userId = getApiLoginMember();
        JSONObject object = JSONObject.parseObject(json);
        Long productId = object.getLong("productId");
        JSONArray ay = object.getJSONArray(object.getString("priceList"));

        String orderNo = "T"+ IdGenerator.getId();
        BigDecimal sum = new BigDecimal(0.00);
        Product p = productService.selectProductById(productId);
        ProductImg img = productImgService.selectProductImgById(p.getImgId());
        List<OrdersItem> array = new ArrayList<>();
        for(int i=0;i<ay.size();i++){
            JSONObject jo = ay.getJSONObject(i);

            Long priceId = jo.getLong("priceId");
            ProductPrice price = convert(productId,priceId+"");
            Integer num = jo.getInteger("addNum");
            OrdersItem o = new OrdersItem();
            o.setProductImg(img.getImgUrl());
            o.setProductNum(num);
            o.setOrderNo(orderNo);
            o.setProductId(productId);
            o.setProductName(p.getProductName());

            if(price != null){
                o.setProductPrice(price.getProductPrice());
                o.setProductUnit(price.getUnit());
                BigDecimal amount = price.getProductPrice().multiply(new BigDecimal(num));
                o.setProductAmount(amount);
                sum = sum.add(amount);
            }
            array.add(o);
        }
        return  AjaxResult.success(ordersService.insertOrders(userId,storeId,array,sum));
    }

    @PostMapping("/submit")
    @ApiOperation("提交订单接口")
    @ResponseBody
    public AjaxResult submitOrder(Long storeId){
        Long userId = getApiLoginMember();

        List<ProductCart> carts = productCartService.selectProductCartOrdersListByUserId(userId);
        List<ItemDTO> item = new ArrayList<>();
        for(ProductCart c : carts){
            ItemDTO dto = new ItemDTO();
            dto.setProductId(c.getProductId());
            dto.setNum(c.getAddNum());
            dto.setPriceId(c.getPriceId());
            item.add(dto);
        }

        String orderNo = "T"+ IdGenerator.getId();

        List<OrdersItem> array = new ArrayList<>();
        BigDecimal sum = new BigDecimal(0.00);
        for (ItemDTO i : item){
            OrdersItem o = new OrdersItem();
            o.setProductId(i.getProductId());
            o.setProductNum(i.getNum());
            o.setOrderNo(orderNo);

            Product p = productService.selectProductById(i.getProductId());
            o.setProductName(p.getProductName());
            o.setProductUnit(p.getProductSpec());

            ProductImg img = productImgService.selectProductImgById(p.getImgId());
            o.setProductImg(img.getImgUrl());

            ProductPrice price = new ProductPrice();
            price.setProductId(i.getProductId());
            price.setKeyId(i.getPriceId());
            List<ProductPrice> plst = productPriceService.selectProductPriceList(price);
            ProductPrice dto = plst.get(0);
            o.setProductPrice(dto.getProductPrice());
            o.setProductUnit(dto.getUnit());
            BigDecimal amount = dto.getProductPrice().multiply(new BigDecimal(i.getNum()));
            o.setProductAmount(amount);
            sum = sum.add(amount);
            array.add(o);
        }
        return  AjaxResult.success(ordersService.insertOrders(userId,storeId,array,sum));
    }

    @PostMapping("/paymentMethod")
    @ApiOperation("提交订单选中支付方式接口（payType=0支付宝，=1微信）")
    @ResponseBody
    public AjaxResult paymentMethod(Integer payType,String orderNo){
        ordersService.updateOrdersPayType(orderNo,payType);
        return  AjaxResult.success();
    }

    @PostMapping("/payStatus")
    @ApiOperation("修改支付状态接口（payStatus= -2支付出错,-1取消支付）")
    @ResponseBody
    public AjaxResult payStatus(Integer payStatus,String orderNo){
        if(payStatus>-1){
            return  AjaxResult.error("非法操作");
        }
        ordersService.updateOrdersPayStatus(orderNo,payStatus);
        return  AjaxResult.success();
    }

    @PostMapping("/confirmReceipt")
    @ApiOperation("确认收货接口")
    @ResponseBody
    public AjaxResult confirmReceipt(String orderNo){
        ordersService.confirmReceipt(orderNo);
        return  AjaxResult.success();
    }

    @PostMapping("/callback")
    @ApiOperation("支付成功回调接口")
    @ResponseBody
    public AjaxResult callback(String orderNo){
        ordersService.updateOrdersCallback(orderNo);

        Orders o = new Orders();
        Orders object = ordersService.selectOrdersList(o).get(0);

        OrdersItem ordersItem = new OrdersItem();
        ordersItem.setOrderNo(orderNo);
        List<OrdersItem> lst = ordersItemService.selectOrdersItemList(ordersItem);
        List<String> ids = new ArrayList<>();
        for(OrdersItem i : lst){
            ids.add(i.getProductId()+"");
        }
        productCartService.deleteProductCartByOrdersProductIds(object.getUserId(),ids);
        return  AjaxResult.success();
    }


}
